<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'  // 导入 axios 库
import easyapi from '../../api'
import { ElMessageBox, ElMessage } from 'element-plus'

// 定义绑定数据
const allData = ref([]);
// 当前页显示的数据 
const tableData = ref([]);

// 分页查询
// 分页状态
const currentPage = ref(1);
const pageSize = ref(15); // 每页显示的数量
const total = ref(0); // 数据总数

// 计算当前页数据
const paginate = () => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    tableData.value = allData.value.slice(start, end);
};
// 挂载页面时查询数据
onMounted(async function() {
    try {
        const result = await easyapi.get("/api/ininventory/all");
        allData.value = result.data;
        total.value = allData.value.length;
        paginate();
    } catch (error) {
        ElMessage({
            type: 'error',
            message: '数据加载失败: ' + (error.response?.data?.message || '未知错误'),
        });
    }
});
// 处理分页变化
const handlePageChange = (newPage) => {
    currentPage.value = newPage;
    paginate();
};


// 查询条件
const query = ref(''); 
async function searchInventory(keyword, isdel = null, isshelf = null) {
    try {
        const response = await axios.get('/api/ininventory/search', {
            params: { keyword, isdel, isshelf }
        });
        console.log('查询结果:', response.data);
        // 搜索结果赋值给 allData，并刷新表格
        allData.value = response.data.data;
        total.value = allData.value.length;
        paginate();
    } catch (error) {
        console.error('查询库存商品失败:', error);
        ElMessage({
            type: 'error',
            message: '查询失败: ' + (error.response?.data?.message || '未知错误'),
        });
    }
}
function searchProducts() {
    searchInventory(query.value);
}
// 重置按钮点击事件，刷新到只查看数据库中 isdel 和 isshelf 为 0 的数据
function resetSearchData() {
    query.value = ''; // 清空搜索条件
    searchInventory('', 0, 0); // 重新加载 isdel 和 isshelf 为 0 的商品
}


// 删除
const del = function(index, row) {
    ElMessageBox.confirm(
        "确定要删除该记录吗?",
        "提示框",
        {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: 'warning',
        }
    ).then(async function() {
        // 提交数据
        await easyapi.del("/api/ininventory/del", row.id);
        // 刷新表格数据
        tableData.value.splice(index, 1);
        // 提示删除成功
        ElMessage({
            type: 'success',
            message: '删除成功',
        });
    });
}


//    编辑
// 控制编辑信息窗口是否显示
const editWinVisible = ref(false);
// 编辑数据绑定对象
const editObject = ref({});
// 保存编辑数据
// 编辑数据的保存
const editSave = async function() {
    try {
        // 确保 URL 中包含 id，editObject.value 应包含其他编辑信息
        await easyapi.putJson(`/api/ininventory/edit/${editObject.value.id}`, editObject.value);
        ElMessage({
            type: 'success',
            message: '保存成功',
        });
        let result = await easyapi.get("/api/ininventory/all");
        allData.value = result.data;
        total.value = allData.value.length;
        paginate();
        editWinVisible.value = false;
    } catch (error) {
        ElMessage({
            type: 'error',
            message: '保存失败: ' + (error.response?.data?.message || '未知错误'),
        });
    }
}

// 点击编辑按钮执行的方法
const edit = function(index, row) {
    // 绑定要修改的数据
    editObject.value = { ...row };
    // 打开对话框
    editWinVisible.value = true;
}
// 关闭编辑窗口
const closeEditWin = () => {
    editWinVisible.value = false;
}

//  获取订单明细弹窗
// 数据和状态
const addWinVisible = ref(false);
const selectedInId = ref(null);
const orderDetails = ref([]);
const productDetails = ref([]);

// 获取出入库详情
async function fetchOrderDetails(in_id) {
    if (!in_id) {
        ElMessage.error('无效的订单 ID');
        return;
    }
    try {
        const response = await easyapi.get(`/api/ininventory/${in_id}`);
        orderDetails.value = response.data;
    } catch (error) {
        ElMessage.error('获取订单详情失败');
    }
}

// 获取单个订单详情
async function fetchProductDetails(in_id) {
    if (!in_id) {
        ElMessage.error('无效的订单 ID');
        return;
    }
    try {
        const response = await easyapi.get(`/api/inorder/${in_id}`);
        productDetails.value = response.data;
    } catch (error) {
        ElMessage.error('获取商品详情失败');
    }
}

// 打开订单明细弹窗
function openAddWin(in_id) {
    selectedInId.value = in_id;
    fetchOrderDetails(in_id);
    fetchProductDetails(in_id);
    addWinVisible.value = true;
}

// 关闭订单明细弹窗
function closeAddWin() {
    addWinVisible.value = false;
    selectedInId.value = null;
    orderDetails.value = [];
    productDetails.value = [];
}

// 导出入库订单的函数
const exportInOrder = async () => {
  try {
    // 直接跳转到文件下载地址
    window.location.href = '/api/inorder/export';

    // 成功提示
    ElMessage.success('文件导出成功');
  } catch (error) {
    console.error('Error exporting orders:', error);
    // 错误提示
    ElMessage.error('文件导出失败，请重试');
  }
}

</script>

<template>
    <!-- 点击按钮刷新 -->
    <el-input 
        v-model="query" 
        placeholder="入库订单或供应商查询" 
        @input="searchProducts"  
        style="flex: 1; max-width: 300px; height: 40px;" 
        size="medium"
        clearable/>

    <el-button type="primary" @click="searchProducts" size="medium">查询</el-button> 
    <el-button type="warning" @click="resetSearchData" size="medium">重置</el-button>
    <el-button type="success" @click="exportInOrder" size="medium">导出入库订单</el-button>

    
    <!-- start 显示所有商品信息的表格 -->
    <el-table :data="tableData" style="width: 100%">
        <el-table-column label="序号" width="80">
            <template v-slot="scope">
                {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
            </template>
        </el-table-column>
        <el-table-column prop="in_id" label="入库订单ID" width="180" />
        <el-table-column prop="in_sums_price" label="订单总金额" width="100" />
        <el-table-column prop="in_name" label="供应商" width="100" />
        <el-table-column prop="in_date" label="时间" width="180" />
        <el-table-column prop="user_name" label="入库人" min-width="100" />

        <el-table-column label="操作" fixed="right">
            <template #default="scope">
                <el-button type="success" size="medium" @click="openAddWin(scope.row.in_id)">查看</el-button>
                <el-button type="warning" @click="edit(scope.$index, scope.row)" disabled>编辑</el-button>
                <el-button type="danger" @click="del(scope.$index, scope.row)" disabled>删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- end 显示商品信息的表格 -->
    
    <!-- start 编辑信息的弹出框 -->
    <el-dialog v-model="editWinVisible" title="编辑" width="500">
        <el-form :model="editObject">
            <el-form-item label="订单总金额" label-width="100">
                <el-input v-model="editObject.in_sums_price" autocomplete="off" />
            </el-form-item>
            <el-form-item label="供应商" label-width="100">
                <el-input v-model="editObject.in_name" autocomplete="off" />
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="closeEditWin">取消</el-button>
                <el-button type="primary" @click="editSave">保存</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- end 编辑信息的弹出框 -->
     
    <!-- start 分页组件 -->
    <el-pagination
        background
        layout="prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="handlePageChange">
    </el-pagination>
    <!-- end 分页组件 -->

    <!-- start 订单明细表的弹出框，修改为查看订单明细 -->
    <el-dialog v-model="addWinVisible" title="该订单明细表" width="800">
       
        <!-- start 显示订单信息的表格 -->
        <el-table :data="orderDetails" style="width: 100%">
            <el-table-column prop="in_id" label="入库订单ID" width="180" />
            <el-table-column prop="in_sums_price" label="订单总金额" width="100" />
            <el-table-column prop="in_name" label="供应商" width="100" />
            <el-table-column prop="in_date" label="时间" width="180" />
            <el-table-column prop="user_name" label="操作人员" min-width="100" />
        </el-table>
        <!-- end 显示订单信息的表格 -->
        
        <!-- start 显示商品信息的表格 -->
        <el-table :data="productDetails" style="width: 100%">
            <el-table-column prop="product_id" label="商品编码" width="110" />
            <el-table-column prop="product_name" label="商品名称" width="110" />
            <el-table-column prop="in_price" label="入库价格" width="110" />
            <el-table-column prop="in_num" label="入库数量" width="110" />
            <el-table-column prop="util" label="单位" width="110" />
            <el-table-column prop="in_sum_price" label="该商品总价" min-width="110" />
        </el-table>
        <!-- end 显示商品信息的表格 -->

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="closeAddWin">关闭</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- end 订单明细表的弹出框 -->
</template>
